package com.mall.controller

import com.mall.entity.Admin
import com.mall.service.AdminService
import com.mall.util.ResponseUtil
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.web.bind.annotation.*

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
@Tag(name = "管理员管理", description = "管理员相关接口")
class AdminController(private val adminService: AdminService) {

    @PostMapping("/register")
    @Operation(summary = "注册管理员", description = "创建一个新的管理员账户")
    fun register(@RequestBody admin: Admin): ResponseUtil<*> {
        return try {
            adminService.register(admin)
            ResponseUtil.success("注册成功", null)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "注册失败")
        }
    }

    @PostMapping("/login")
    @Operation(summary = "管理员登录", description = "管理员登录并返回JWT令牌")
    fun login(@RequestBody loginData: Map<String, String>): ResponseUtil<*> {
        return try {
            val username = loginData["username"] ?: ""
            val password = loginData["password"] ?: ""
            val result = adminService.login(username, password)
            ResponseUtil.success("登录成功", result)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(message = e.message ?: "登录失败")
        }
    }

    @PutMapping("/update")
    @Operation(summary = "更新管理员信息", description = "更新当前登录管理员的信息")
    fun update(@RequestBody admin: Admin): ResponseUtil<*> {
        return try {
            adminService.update(admin)
            ResponseUtil.success("更新成功", null)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "更新失败")
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除管理员", description = "根据ID删除管理员")
    fun delete(@PathVariable id: Long): ResponseUtil<*> {
        return try {
            adminService.delete(id)
            ResponseUtil.success("删除成功", null)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "删除失败")
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获取管理员列表", description = "分页获取管理员列表")
    fun list(
        @RequestParam(defaultValue = "1") page: Int,
        @RequestParam(defaultValue = "10") pageSize: Int
    ): ResponseUtil<*> {
        return try {
            val result = adminService.list(page, pageSize)
            ResponseUtil.success(result)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "获取列表失败")
        }
    }
}